/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mona
 */
public class AddToCart extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        
        try {
            //response.setContentType("text/html;charset=UTF-8");            
            /* Connection With Database */
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/Shopping", "root", "asmaaelmasry");
            
           String pId = request.getParameter("productId");
            String q   = request.getParameter("quantity");
            HttpSession sess =  request.getSession(false);
            
            if( AddToCart.isInteger(pId) && AddToCart.isInteger(q) && sess !=null ){
                
                Integer uid = Integer.parseInt((String) sess.getAttribute("id"));
                Integer pIdInteger =  Integer.parseInt(pId);
                Integer qInteger = Integer.parseInt(q);
                
                PreparedStatement enoughQuantity =  (PreparedStatement) con.prepareStatement("SELECT quantity FROM Product WHERE id = ?");
                enoughQuantity.setInt(1, pIdInteger );
                ResultSet enoughQuantityRs = enoughQuantity.executeQuery();
                if( !enoughQuantityRs.next() ||  enoughQuantityRs.getInt(1) < qInteger ){
                    out.print("-1");                    
                    return;
                }
                
                PreparedStatement isExistStmt =  (PreparedStatement) con.prepareStatement("SELECT COUNT(*) AS exist FROM Cart WHERE status=0 and userId = ? AND productId = ? ");
                isExistStmt.setInt(1, uid );
                isExistStmt.setInt(2, pIdInteger );
                ResultSet rs = isExistStmt.executeQuery();
                rs.next();
                int exist = rs.getInt(1);

                PreparedStatement ps,ps2;
                int status=0;
                if(exist == 0)
                    ps =  (PreparedStatement) con.prepareStatement("INSERT INTO Cart (quantity,status,userId,productId) VALUES (?,?,?,?) ");
                else
                    ps =  (PreparedStatement) con.prepareStatement("UPDATE Cart SET quantity = quantity + ? , status= ? WHERE userId = ? AND productId = ? ");

                if(qInteger > 0 && pIdInteger > 0 ){
                    ps.setInt(1, qInteger  );
                    ps.setInt(2,status );
                    ps.setInt(3, uid );
                    ps.setInt(4, pIdInteger  );
                    
                    ps.executeUpdate();
                    
                    ps2 = (PreparedStatement) con.prepareStatement("UPDATE Product SET quantity = quantity - ? WHERE id = ? ");
                    ps2.setInt(1, qInteger  );
                    ps2.setInt(2, pIdInteger  );
                    ps2.executeUpdate();
                    
                    PreparedStatement allQStmt =  (PreparedStatement) con.prepareStatement("SELECT SUM(quantity) As bagCount from Cart where status=0 and userId = ? ");
                    allQStmt.setInt(1, uid );

                    ResultSet rs2 = allQStmt.executeQuery();
                    rs2.next();
                    
                    out.print(rs2.getInt(1));
                    
                    return;
                }
            }
           
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AddToCart.class.getName()).log(Level.SEVERE.SEVERE, null, ex);
        } catch (SQLException ex) {
             Logger.getLogger(AddToCart.class.getName()).log(Level.SEVERE.SEVERE, null, ex);
        }
        out.print("0");        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);        
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    public static boolean isInteger(String s) {
        try{ 
            Integer.parseInt(s); 
        }catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }
}
